package com.yff.tuan.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yff.tuan.api.ApiResult;
import com.yff.tuan.api.Result;
import com.yff.tuan.model.RoleExample;
import com.yff.tuan.model.User;
import com.yff.tuan.model.UserExample;
import com.yff.tuan.model.UserExample.Criteria;
import com.yff.tuan.model.WxUserBind;
import com.yff.tuan.model.WxUserExample;
import com.yff.tuan.service.RoleService;
import com.yff.tuan.service.UserService;
import com.yff.tuan.service.WxUserService;
import com.yff.tuan.util.AESUtil;
import com.yff.tuan.util.Page;
import com.yff.tuan.util.StringUtil;
import com.yff.tuan.vo.UserVo;

@Controller
@RequestMapping("/user")
public class UserController {
	
	private Logger LOG = LoggerFactory.getLogger(UserController.class);
	@Autowired
	UserService service;
	@Autowired
	RoleService roleService;
	@Autowired
	WxUserService wxUserService;
	
	@RequestMapping("/list")
	public String list(Model model,Integer pageNum,HttpServletRequest request,HttpServletResponse response){
		
		Page<UserVo> page = service.queryByPage(null == pageNum ? 1 : pageNum);
		model.addAttribute("page", page);
		model.addAttribute("roles", roleService.query(new RoleExample()));
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(2);
		model.addAttribute("userLeaders", service.query(example));
		model.addAttribute("wxUsers", wxUserService.query(new WxUserExample()));
		return "/user_list";
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public Object del(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		if(null == id) {
			return ApiResult.ERROR(Result.INVALID_PARAMETERS);
		}
		return ApiResult.SUCCESS(service.del(id));
	}
	@RequestMapping("/updatepassword")
	@ResponseBody
	public Object updatepassword(Model model,Integer userId,String password,HttpServletRequest request,HttpServletResponse response){
		User user = new User();
		user.setId(userId);
		user.setPassword(StringUtil.isEmpty(password)?AESUtil.Encrypt("123456"):AESUtil.Encrypt(password));
		return ApiResult.SUCCESS(service.updateByPrimaryKeySelective(user));
	}
	
	
	@RequestMapping("/add")
	@ResponseBody
	public Object add(Model model,User user,HttpServletRequest request,HttpServletResponse response){
		if(null == user) {
			return ApiResult.ERROR(Result.INVALID_PARAMETERS);
		}
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		UserExample example = new UserExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andNameEqualTo(user.getName());
		List<User> users = service.query(example);
		if(null != users && !users.isEmpty()) {
			return ApiResult.ERROR(Result.ALREADY_EXIST_USER_NAME);
		}
		user.setPassword(AESUtil.Encrypt(user.getPassword()));
		return ApiResult.SUCCESS(service.insert(user));
	}
	
	@RequestMapping("/updateUser")
	public String updateUser(Model model,int userId,HttpServletRequest request,HttpServletResponse response){
		UserVo user = service.find(userId);
		if(null != user){
			user.setPassword(AESUtil.Decrypt(user.getPassword()));
			model.addAttribute("user", user);
			model.addAttribute("roles", roleService.query(new RoleExample()));
			UserExample example = new UserExample();
			Criteria criteria = example.createCriteria();
			criteria.andRoleIdEqualTo(2);
			model.addAttribute("userLeaders", service.query(example));
			model.addAttribute("wxUsers", wxUserService.query(new WxUserExample()));
		}
		return "/user_update";
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public Object updateUser(Model model,@RequestBody Map<String, Object> object,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> resMap = new HashMap<String, Object>();
		if(null != object){
			try {
				User user = new User();
				int id = 0;
				if(object.containsKey("id")) {
					id = Integer.parseInt(String.valueOf(object.get("id")));
					user.setId(id);
				}
				if(object.containsKey("name")) {
					user.setName(String.valueOf(object.get("name")));
				}
				if(object.containsKey("password")) {
					user.setPassword(AESUtil.Encrypt(String.valueOf(object.get("password"))));
				}
				if(object.containsKey("roleId")) {
					user.setRoleId(Integer.parseInt(String.valueOf(object.get("roleId"))));
				}
				service.updateByPrimaryKeySelective(user);
			
				if(object.containsKey("wxIds")) {
					@SuppressWarnings("unchecked")
					List<String> wxIds= (List<String>) object.get("wxIds");
					if(null != wxIds && wxIds.size()>0) {
						List<WxUserBind> binds = new ArrayList<WxUserBind>();
						for(String wxId: wxIds) {
							WxUserBind bind = new WxUserBind();
							bind.setUserId(id);
							bind.setWxId(Integer.parseInt(wxId));
							binds.add(bind);
						}
						wxUserService.updateWxUser(id, binds);
					}
				}
				resMap.put("update", true);
			} catch (Exception e) {
				e.printStackTrace();
				resMap.put("update", false);
			}
		}else {
			resMap.put("update", false);
		}
		return resMap;
	}
	
	@RequestMapping("/bind")
	@ResponseBody
	public Object bind(Model model,User user,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("binded", false);
		if(null != user && user.getId() != null) {
			int count = service.updateByPrimaryKeySelective(user);
			if(count>0) {
				map.put("binded", true);
			}
		}
		return map;
	}
}
